﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO;
using System.Xml;
using System.ServiceModel.Syndication;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
using System.Collections;
using OnlineVideos.Entities;
using OnlineVideos.Data;
using System.Xml.Linq;
using Common.Library;
using System.Reflection;
using InsertIntoDataBase;
using HtmlAgilityPack;
using System.Collections.ObjectModel;
using System.IO.IsolatedStorage;
using OnlineVideos.ViewModels;
using System.Threading.Tasks;
using Common.Utilities;


namespace OnlineVideos.Views
{
    public class Extraparam
    {
        public string Title
        {
            get;
            set;
        }
        public string TileDesc
        {
            get;
            set;
        }
        public string ImageUrl
        {
            get;
            set;
        }
        public Visibility Control
        {
            get;
            set;
        }
        public int Id
        {
            get;
            set;
        }
    }
    public class DownloadBlogInfo
    {
        public List<ShowLinks> showlinks
        {
            get;
            set;
        }
        public ShowList show
        {
            get;
            set;
        }
        public List<PlayListTable> Play
        {
            get;
            set;
        }
        public WebInformation web
        {
            get;
            set;
        }
        public Extraparam extra
        {
            get;
            set;
        }
        public ShowCategories sc
        {
            get;
            set;
        }
        public CategoriesByShowID cbs
        {
            get;
            set;
        }
       
    }
    public partial class OnlineShare : PhoneApplicationPage
    {
        int count = 10;
        public string CatName = string.Empty;
        public bool sortDate = false;
        public ObservableCollection<DownloadBlogInfo> DownloadList = default(ObservableCollection<DownloadBlogInfo>);
        public int startIndex = 1;
        public int maxresults = 10;
        public List<int> ListId = new List<int>();
        public bool WebclientStatus = false;
        public OnlineShare()
        {
            InitializeComponent();
            Loaded += OnlineShare_Loaded;
        }
        private void LoadAds()
        {
            try
            {
                PageHelper.LoadAdControl(LayoutRoot, adstaCast, 2);
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in LoadAds Method In SongDetails file", ex);
                string excepmess = "Exception in LoadAds Method In SongDetails file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }

        }

        void OnlineShare_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                LoadAds();
                List<string> catlist = new List<string>();
                catlist.Add("--Select Type--");
                
                foreach (string cat in Task.Run(async()=>await Constants.connection.Table<BlogCategoryTable>().ToListAsync()).Result.Select(i => i.BlogCategory))
                {
                    catlist.Add(cat);
                }
                CategoryList.ItemsSource = catlist;
                CategoryList.SelectionChanged += CategoryList_SelectionChanged_1;
                CategoryList.ItemsSource = catlist;
                CategoryList.SelectedIndex = 0;
                TbSearch.Text = string.Empty;
                sortDate = false;
                DownloadList = new ObservableCollection<DownloadBlogInfo>();
                OnlineList.ItemsSource = DownloadList;
                CategoryList.SelectionChanged += CategoryList_SelectionChanged_1;
                startIndex = 1;
                maxresults = 10;
                string selecteditem = CategoryList.SelectedItem.ToString();
                BlogCategoryTable bt = Task.Run(async () => await Constants.connection.Table<BlogCategoryTable>().Where(i => i.BlogCategory == selecteditem).FirstOrDefaultAsync()).Result;
                if (bt != null)
                {
                    loaddata(bt.BlogUrl + "start-index=" + startIndex + "&max-results=" + maxresults + "&alt=rss");
                }
            }
            catch (Exception ex)
            {
                
              
            }
        }
        public void loaddata(string url)
        {
            try
            {
                //if (WebclientStatus == false)
                //{
                   notavailable.Visibility = Visibility.Collapsed;
                    string feed = string.Empty;
                    WebClient wclient = new WebClient();
                    wclient.OpenReadCompleted += (sender1, e1) =>
                    {
                        if (e1.Error != null)
                            return;
                        int BindId = 0;
                        Stream str = e1.Result;
                        XmlReader response = XmlReader.Create(str);
                        SyndicationFeed feeds = SyndicationFeed.Load(response);
                        string[] stringSeparators = new string[] { "??" };
                        if (feeds.Items.Count() > 0)
                        {
                            foreach (SyndicationItem f in feeds.Items)
                            {
                                bool exists = false;
                                foreach (SyndicationCategory sc in f.Categories)
                                {
                                    if (sc.Name == "hide")
                                    {
                                        exists = true;
                                    }
                                }

                                if (exists == false)
                                {
                                    int index = 0;
                                    string[] xml = new string[2];
                                    DownloadBlogInfo db = new DownloadBlogInfo();
                                    db.extra = new Extraparam();
                                    feed = HttpUtility.HtmlDecode(Regex.Replace(f.Summary.Text, "<[^>]+?>", ""));
                                    HtmlDocument doc = new HtmlDocument();
                                    doc.LoadHtml(f.Summary.Text);
                                    foreach (HtmlNode node in doc.DocumentNode.SelectNodes(" //img"))
                                    {
                                        if (node.OuterHtml.Contains("src"))
                                        {
                                            db.extra.ImageUrl = node.Attributes["src"].Value;
                                        }
                                    }
                                    foreach (string stri in feed.Split(stringSeparators, StringSplitOptions.None))
                                    {
                                        xml[index] = stri;
                                        index++;
                                    }
                                    BindId++;
                                    db.extra.Id = BindId;
                                    TextReader read = new StringReader(xml[1].ToString());
                                    XDocument xdoc = XDocument.Load(read);

                                    var TablesList = Task.Run(async () => await Constants.connection.Table<ShareTables>().ToListAsync()).Result.OrderBy(i => i.TableOrder);
                                    if (ResourceHelper.ProjectName == "Video Mix")
                                    {
                                        db.Play = new List<PlayListTable>();
                                        db.showlinks = new List<ShowLinks>();
                                    }
                                    foreach (var TableName in TablesList.GroupBy(i => i.TableName))
                                    {
                                        XElement Param = default(XElement);
                                        List<XElement> Param1 = default(List<XElement>);
                                        List<XElement> param2 = default(List<XElement>);
                                        Assembly DataAssembly = Assembly.Load(Constants.NamespaceForData);
                                        Type TableType = DataAssembly.GetType(Constants.NamespaceForData + "." + TableName.Key.ToString());
                                        object TableInstance = Activator.CreateInstance(TableType);
                                        Convert.ChangeType(TableInstance, TableType, null);
                                        var InsertType = typeof(InsertData<>);
                                        Type[] Typeargs = { TableType };
                                        var makeme = InsertType.MakeGenericType(Typeargs);
                                        object InsertInstance = Activator.CreateInstance(makeme);
                                        if (TableName.Key.ToString() == "PlayListTable")
                                        {
                                            Param1 = xdoc.Descendants("NewDataSet").Elements().Where(i => i.Name == TableName.Key.ToString()).ToList();
                                            InsertData<PlayListTable> playlist = new InsertData<PlayListTable>();
                                            foreach (XElement xele in Param1)
                                            {
                                                db.Play.Add(playlist.XMLToEntity(xele.ToString()));
                                            }
                                        }
                                        else if (TableName.Key.ToString() == "ShowLinks")
                                        {
                                            param2 = xdoc.Descendants("NewDataSet").Elements().Where(i => i.Name == TableName.Key.ToString()).ToList();
                                            InsertData<ShowLinks> Showlinks = new InsertData<ShowLinks>();
                                            foreach (XElement xele in param2)
                                            {
                                                db.showlinks.Add(Showlinks.XMLToEntity(xele.ToString()));
                                            }
                                        }
                                        else
                                        {
                                            Param = xdoc.Descendants("NewDataSet").Elements().Where(i => i.Name == TableName.Key.ToString()).FirstOrDefault();
                                        }
                                        if (Param != null)
                                        {
                                            string propertyname = string.Empty;
                                            PropertyInfo[] ConditionProperty = db.GetType().GetProperties();
                                            foreach (PropertyInfo property in ConditionProperty)
                                            {
                                                if (property.PropertyType == TableType)
                                                {
                                                    propertyname = property.Name;
                                                    break;
                                                }
                                            }

                                            TableInstance = InsertInstance.GetType().GetMethod("XMLToEntity").Invoke(InsertInstance, new object[] { Param.ToString() });

                                            db.GetType().GetProperty(propertyname).SetValue(db, TableInstance, null);
                                        }
                                    }
                                    db.extra.Control = Visibility.Visible;
                                    db.extra.TileDesc = xml[0].ToString();
                                    db.extra.Title = db.show.Title;
                                    DownloadList.Add(db);
                                }
                                str.Close();

                            }
                            if (DownloadList.Count() > 0)
                            {
                                DownloadBlogInfo db1 = new DownloadBlogInfo();
                                db1.extra = new Extraparam();
                                db1.extra.Title = "get more..";
                                db1.extra.Control = Visibility.Collapsed;
                                DownloadList.Add(db1);
                            }
                            else
                            {
                                notavailable.Visibility = Visibility.Visible;
                            }
                        }
                        else
                        {
                            if (OnlineList.Items.Count==0)
                            notavailable.Visibility = Visibility.Visible;
                            foreach (DownloadBlogInfo db in DownloadList)
                            {
                                if (db.extra.Title == "get more..")
                                {
                                    DownloadList.Remove(db);
                                }
                            }
                        }



                    };

                    wclient.OpenReadAsync(new Uri(url, UriKind.RelativeOrAbsolute));
                    WebclientStatus = true;
                //}
            }
            catch (Exception ex)
            {


            }
        
        }
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(TbSearch.Text))
                {
                    SearchManager.SaveSearchHistory(TbSearch.Text);
                    startIndex = 1;
                    maxresults = 10;
                    sortDate = false;
                    DownloadList.Clear();
                   
                    BlogCategoryTable bt = Task.Run(async () => await Constants.connection.Table<BlogCategoryTable>().Where(i => i.BlogCategory == CatName).FirstOrDefaultAsync()).Result;
                    loaddata(bt.BlogUrl + "start-index=" + startIndex + "&max-results=" + maxresults + "&category=" + TbSearch.Text + "&alt=rss");
                }
                //http://www.blogger.com/feeds/blogID/posts/default?updated-min=2008-03-16T00:00:00&updated-max=2008-03-24T23:59:59&orderby=updated
            }
            catch (Exception ex)
            {
                
           
            }
        }

        private void sort_Click_1(object sender, EventArgs e)
        {
            try
            {
                startIndex = 1;
                maxresults = 10;
                sortDate = true;
                DownloadList.Clear();
                TbSearch.Text = string.Empty;

                BlogCategoryTable bt = Task.Run(async () => await Constants.connection.Table<BlogCategoryTable>().Where(i => i.BlogCategory == CatName).FirstOrDefaultAsync()).Result;
                WebclientStatus = false;
                loaddata(bt.BlogUrl + "start-index=" + startIndex + "&max-results=" + maxresults + "&orderby=updated&alt=rss");
            }
            catch (Exception ex)
            {
                
               
            }
        }

        private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
        {
            try
            {
                foreach (int id in ListId)
                {
                    int catId = 0;
                    DownloadBlogInfo di = OnlineList.ItemsSource.Cast<DownloadBlogInfo>().Where(i => i.extra.Id == id).FirstOrDefault();
                    WebClient wb = new WebClient();
                    PropertyInfo[] ConditionProperty = di.GetType().GetProperties();

                    foreach (PropertyInfo property in ConditionProperty)
                    {
                        Assembly DataAssembly = Assembly.Load(Constants.NamespaceForData);
                        if (property.Name.ToString() == "Play")
                        {
                            foreach (PlayListTable list in di.Play)
                            {
                                list.ShowID = di.show.ShowID;
                            }
                        }
                        else if (property.Name.ToString() == "showlinks")
                        {
                            foreach (ShowLinks list in di.showlinks)
                            {
                                list.ShowID = di.show.ShowID;
                            }
                        }
                        //if (property.PropertyType.Name.ToString().StartsWith("List"))
                        //{
                        //    foreach (PlayListTable list in di.Play)
                        //    {
                        //        list.ShowID = di.show.ShowID;
                        //    }
                        //}
                        else
                        {
                            Type TableType = DataAssembly.GetType(Constants.NamespaceForData + "." + property.PropertyType.Name.ToString());
                            if (TableType != null)
                            {

                                if (di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null) != null)
                                {
                                    if (property.PropertyType.Name.ToString() == "ShowCategories")
                                    {
                                        string categoryName=di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null).GetType().GetProperty("CategoryName").GetValue(di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null), null).ToString();
                                        if (Task.Run(async () => await Constants.connection.Table<ShowCategories>().Where(i => i.CategoryName == categoryName).ToListAsync()).Result.Count > 0)
                                        {
                                            catId = Task.Run(async () => await Constants.connection.Table<ShowCategories>().Where(i => i.CategoryName == categoryName).FirstOrDefaultAsync()).Result.CategoryID;
                                            di.GetType().GetProperty(property.Name.ToString()).SetValue(di, new ShowCategories(), null);
                                        }
                                        else
                                        {
                                            di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null).GetType().GetProperty("CategoryID").SetValue(di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null), (Task.Run(async () => await Constants.connection.Table<ShowCategories>().FirstOrDefaultAsync()).Result != null) ? Task.Run(async () => await Constants.connection.Table<ShowCategories>().ToListAsync()).Result.Max(i => i.CategoryID) + 1 : 1, null);
                                            catId = (int)di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null).GetType().GetProperty("CategoryID").GetValue(di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null), null);
                                        }
                                    }
                                    else if (property.PropertyType.Name.ToString() == "CategoriesByShowID")
                                    {
                                       
                                        di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null).GetType().GetProperty("CatageoryID").SetValue(di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null), catId, null);
                                        di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null).GetType().GetProperty("ShowID").SetValue(di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null), (Task.Run(async () => await Constants.connection.Table<ShowList>().FirstOrDefaultAsync()).Result != null) ? di.show.ShowID : 1, null);
                                    }
                                    else
                                    {

                                      
                                        if (property.PropertyType.Name.ToString() == "ShowList")
                                        {
                                            di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null).GetType().GetProperty("ShowID").SetValue(di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null), (Task.Run(async () => await Constants.connection.Table<ShowList>().FirstOrDefaultAsync()).Result != null) ? Task.Run(async () => await Constants.connection.Table<ShowList>().ToListAsync()).Result.Max(i => i.ShowID) + 1 : 1, null);
                                            di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null).GetType().GetProperty("TileImage").SetValue(di.show, di.show.ShowID.ToString() + ".jpg", null);
                                            di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null).GetType().GetProperty("CreatedDate").SetValue(di.show, System.DateTime.Now, null);
                                        }
                                        else
                                        {
                                            di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null).GetType().GetProperty("ShowID").SetValue(di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null), (Task.Run(async () => await Constants.connection.Table<ShowList>().FirstOrDefaultAsync()).Result != null) ? di.show.ShowID : 1, null);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    wb.OpenReadAsync(new Uri(di.extra.ImageUrl, UriKind.RelativeOrAbsolute), di.show.ShowID.ToString() + ".jpg");
                    wb.OpenReadCompleted += wb_OpenReadCompleted;
                    SaveToDatabase(di);

                    History objHistory = new History();
                    objHistory.SaveMovieHistory(di.show.ShowID.ToString(), "");

                }
                NavigationService.GoBack();
            }
            catch (Exception ex)
            {
                
               
            }
        }

        void wb_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            try
            {
                if (e.Result != null)
                {
                    //if (!Storage.DirectoryExists(ResourceHelper.ProjectName))
                    //{
                    //    Storage.CreateDirectory(ResourceHelper.ProjectName);
                    //}
                    if (!Storage.DirectoryExists("/Images"))
                    {
                        Storage.CreateDirectory("/Images");
                    }
                    using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        using (var local = myIsolatedStorage.OpenFile(Constants.ImagePath + e.UserState.ToString(), System.IO.FileMode.OpenOrCreate))
                        {
                            byte[] buffer = new byte[e.Result.Length / 4];
                            int bytesRead = -1;
                            e.Result.Position = 0;
                            while ((bytesRead = e.Result.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                local.Write(buffer, 0, bytesRead);
                            }

                            local.Close();
                            local.Dispose();
                            myIsolatedStorage.Dispose();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                
              
            }
        }
        private void SaveToDatabase(DownloadBlogInfo di)
        {
            try
            {
               
                PropertyInfo[] ConditionProperty = di.GetType().GetProperties();
                foreach (PropertyInfo property in ConditionProperty)
                {
                    Assembly DataAssembly = Assembly.Load(Constants.NamespaceForData);
                    Type TableType = DataAssembly.GetType(Constants.NamespaceForData + "." + property.PropertyType.Name.ToString());
                    //if (property.PropertyType.Name.ToString().StartsWith("List"))
                    //{
                    //    Constants.connection.InsertAllAsync(di.Play);
                    //}
                    if (property.Name == "Play")
                    {
                        Constants.connection.InsertAllAsync(di.Play);

                    }
                    if (property.Name == "showlinks")
                    {
                        Constants.connection.InsertAllAsync(di.showlinks);

                    }
                    if (TableType != null)
                    {
                        object TableInstance = Activator.CreateInstance(TableType);

                        if (di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null) != null)
                        {
                            var InsertType = typeof(InsertData<>);
                            Type[] Typeargs = { TableType };
                            var makeme = InsertType.MakeGenericType(Typeargs);
                            object InsertInstance = Activator.CreateInstance(makeme);
                            InsertInstance.GetType().GetProperty("ParameterList").SetValue(InsertInstance, di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null), null);
                            InsertInstance.GetType().GetMethod("Insert").Invoke(InsertInstance, null);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                
              
            }
           
        }
        private void CheckBox_Checked_1(object sender, RoutedEventArgs e)
        {
            if (!ListId.Contains((int)(sender as CheckBox).Tag))
                ListId.Add((int)(sender as CheckBox).Tag);
        }

        private void CheckBox_Unchecked_1(object sender, RoutedEventArgs e)
        {
            if (ListId.Contains((int)(sender as CheckBox).Tag))
                ListId.Remove((int)(sender as CheckBox).Tag);
        }

       

       
        private void Tbtitle_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
        {
            try
            {
                if ((sender as TextBlock).Text == "get more..")
                {
                    foreach (DownloadBlogInfo db in DownloadList.ToList())
                    {
                        if (db.extra.Title == "get more..")
                        {
                            DownloadList.Remove(db);
                        }
                    }

                    startIndex = count + 1;
                    count = startIndex + 9;
                    maxresults = 10;
                    if (!string.IsNullOrEmpty(TbSearch.Text))
                    {
                        
                        BlogCategoryTable bt = Task.Run(async () => await Constants.connection.Table<BlogCategoryTable>().Where(i => i.BlogCategory == CatName).FirstOrDefaultAsync()).Result;
                        loaddata(bt.BlogUrl + "start-index=" + startIndex + "&max-results=" + maxresults + "&category=" + TbSearch.Text + "&alt=rss");
                    }
                    else if (sortDate == true)
                    {
                        
                        BlogCategoryTable bt = Task.Run(async () => await Constants.connection.Table<BlogCategoryTable>().Where(i => i.BlogCategory == CatName).FirstOrDefaultAsync()).Result;
                        loaddata(bt.BlogUrl + "start-index=" + startIndex + "&max-results=" + maxresults + "&orderby=updated&alt=rss");
                    }
                    else
                    {
                        
                        BlogCategoryTable bt = Task.Run(async () => await Constants.connection.Table<BlogCategoryTable>().Where(i => i.BlogCategory == CatName).FirstOrDefaultAsync()).Result;
                        loaddata(bt.BlogUrl + "start-index=" + startIndex + "&max-results=" + maxresults + "&alt=rss");
                    }
                }
            }
            catch (Exception ex)
            {
                
               
            }
        }

        private void CategoryList_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {

           string mode = CategoryList.SelectedItem.ToString();
          
           try
           {
               if (CategoryList.SelectedIndex == -1)
                   return;
               if (CategoryList.SelectedIndex != 0)
               {
                   DownloadList.Clear();
                   CatName = (sender as ListPicker).SelectedItem.ToString();
                   startIndex = 1;
                   maxresults = 10;
                  
                   BlogCategoryTable bt = Task.Run(async () => await Constants.connection.Table<BlogCategoryTable>().Where(i => i.BlogCategory == CatName).FirstOrDefaultAsync()).Result;
                   WebclientStatus = false;
                   loaddata(bt.BlogUrl + "start-index=" + startIndex + "&max-results=" + maxresults + "&alt=rss");
                   CategoryList.SelectedIndex = -1;
               }
           }
           catch (Exception)
           {
               
              
           }
        }

        private void TbSearch_KeyUp_1(object sender, System.Windows.Input.KeyEventArgs e)
        {
            try
            {
                if (e.Key ==System.Windows.Input.Key.Enter)
                {
                    if (e.Key == System.Windows.Input.Key.Enter)
                    {
                        if (!string.IsNullOrEmpty(TbSearch.Text))
                        {
                            SearchManager.SaveSearchHistory(TbSearch.Text);
                            startIndex = 1;
                            maxresults = 10;
                            sortDate = false;
                            DownloadList.Clear();
                            
                            BlogCategoryTable bt = Task.Run(async () => await Constants.connection.Table<BlogCategoryTable>().Where(i => i.BlogCategory == TbSearch.Text).FirstOrDefaultAsync()).Result;
                            WebclientStatus = false;
                            loaddata(bt.BlogUrl + "category=" + TbSearch.Text + "&alt=rss");
                        }
                    }
                }

                e.Handled = true;
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in videoMediaElement_KeyUp_1 Event In Youtube.xaml.cs file", ex);


            }
        }

        private void TextBlock_Loaded_1(object sender, RoutedEventArgs e)
        {
            TextBlock tb = sender as TextBlock;
            if (tb.Text == "--Select Type--")
            {
                tb.Visibility = Visibility.Collapsed;
                tb.Loaded -= TextBlock_Loaded_1;
            }
        }

    }
}